package javbot.mail;

import javbot.GlobalClass;
import javbot.RobotRunner;
import javbot.script.ScriptParser;

public class MailChecker extends Thread{

	// Checks email for javbot script;
	MailReader mr;
	private int intervalMinutes = 1;
	
	public MailChecker(String mailServer, String login, String password) {
		mr = new MailReader(mailServer, login, password);
	}

	private void checkAtInterval() {
		while (GlobalClass.mailProps.isEnableMailChecker()) {
			String mails[] = mr.getMail();
			if (mails.length > 0)
				for (int i=0; i < mails.length; i++) {
					System.out.println("Checking mail " + (i + 1) + " of "  + mails.length);
					if (MailParser.isJavbotMail(mails[i])) {
						System.out.println("Mail " + (i + 1) + " is a Javbot mail");
						runScript(MailParser.getJavbotScript(mails[i]));
						
					} else {
						System.out.println("Mail " + (i + 1) + " is not a Javbot mail");
					}
				}
			else
				System.out.println("No mails");
			sleepMinutes(intervalMinutes);
		}
	}

	private void runScript(String script) {
		RobotRunner.runCommandList(ScriptParser.parseScript(script));
	}
	
	private void sleepMinutes(int mins) {
		try {
			System.out.println("Waiting " + mins + " minutes...");
			Thread.sleep(60000 * mins);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}

	public void run() {
		checkAtInterval();
	}

	public void setCheckInterval(int minutes) {
		this.intervalMinutes = minutes;
	}
	
	

	
}
